# -*- coding: utf-8 -*-
"""
HaaS506 RTU 数据服务模块
简化版本 - 数据采集和上传
"""

import utime
import rtu_config
import rtu_modbus
import rtu_gpio
import rtu_mqtt
import rtu_storage
import rtu_network
import rtu_adc

# 数据采集状态
_last_collection_time = 0
_packet_sequence = 0  # 包序列号(1-65535循环)

def init():
    """初始化数据服务"""
    print("[DATA] Data service initialized")
    return True

def collect_data(emergency=False):
    """采集数据
    
    Args:
        emergency: 是否为紧急采集（断电或电流异常），紧急采集不对齐时间
    """
    global _last_collection_time
    
    try:
        print("[DATA-DEBUG] Starting data collection... (emergency={})".format(emergency))
        
        # 在采集开始时立即记录时间，确保时间戳准确
        collection_start_time = utime.time()
        _last_collection_time = collection_start_time
        
        # 采集各种原始数据，每个步骤都添加异常保护
        try:
            modbus_data = rtu_modbus.read_all_devices() or {}
        except Exception as e:
            print("[DATA] Modbus read error: {}, using empty data".format(e))
            modbus_data = {}
        
        try:
            gpio_data = rtu_gpio.read_digital_inputs() or {}
        except Exception as e:
            print("[DATA] GPIO read error: {}, using empty data".format(e))
            gpio_data = {}
        
        try:
            adc_data = rtu_adc.collect_adc_data() or {}
        except Exception as e:
            print("[DATA] ADC read error: {}, using empty data".format(e))
            adc_data = {}
        
        try:
            system_data = _collect_system_data() or {}
        except Exception as e:
            print("[DATA] System data error: {}, using empty data".format(e))
            system_data = {}
        
        # 格式化为服务器期望的格式，传入采集开始时间和紧急标志
        formatted_data = _format_server_data(modbus_data, gpio_data, adc_data, system_data, collection_start_time, emergency)
        
        print("[DATA-DEBUG] formatted_data: {}".format(formatted_data))
        
        # 如果网络和MQTT都正常，直接上传
        if rtu_config.g_network_ready and rtu_config.g_mqtt_connected:
            print("[DATA-DEBUG] Network and MQTT OK, uploading immediately...")
            if rtu_mqtt.publish_data(formatted_data):
                print("[DATA] Data uploaded immediately")
                # 上传成功，不需要保存
            else:
                print("[DATA] Immediate upload failed, caching data")
                # 上传失败，保存到缓存
                rtu_storage.cache_data(formatted_data)
        else:
            # 网络或MQTT不正常，保存到缓存
            print("[DATA-DEBUG] Network or MQTT not ready, caching data")
            rtu_storage.cache_data(formatted_data)
        
        print("[DATA] Data collected: {} fields".format(len(formatted_data)))
        return formatted_data
        
    except Exception as e:
        print("[DATA] Data collection error: {}".format(e))
        return None

def _format_server_data(modbus_data, gpio_data, adc_data, system_data, collection_time=None, emergency=False):
    """格式化数据为服务器期望的格式
    
    Args:
        emergency: 是否为紧急采集，紧急采集不对齐时间
    """
    global _packet_sequence
    
    try:
        # 获取设备信息
        device_sn = rtu_config.get_device_sn()
        hardware_version = rtu_config.get_config("device.hardware", "HY-APT100")
        software_version = rtu_config.get_config("system.version", "1.0.0")
        
        # 递增包序列号(1-65535循环)
        _packet_sequence = (_packet_sequence % 65535) + 1
        
        # 获取SIM卡信息
        imei = ""
        ccid = "" 
        cnum = ""
        try:
            from modem import sim
            # 获取IMEI
            try:
                imei = sim.getImei() or ""
            except:
                imei = ""
            
            # 获取CCID
            try:
                ccid = sim.getIccid() or ""
            except:
                ccid = ""
                
            # 获取CNUM (电话号码)
            try:
                cnum = sim.getPhoneNumber() or ""
            except:
                cnum = ""
                
            print("[DATA-DEBUG] SIM info - IMEI: {}, CCID: {}, CNUM: {}".format(imei, ccid, cnum))
        except Exception as e:
            print("[DATA-DEBUG] SIM info retrieval error: {}".format(e))
        
        # 使用传入的采集时间，如果没有传入则使用当前时间
        if collection_time is None:
            collection_time = utime.time()
        
        # 获取采集间隔配置
        collection_interval = rtu_config.get_config("intervals.data_collection", 60)
        
        # 只有正常采集（非紧急）且采集间隔是60秒的倍数时，才对齐到整分钟
        if not emergency and collection_interval % 60 == 0:
            # 将时间对齐到整分钟（秒数设为0）
            aligned_time = (collection_time // 60) * 60
            collection_time = aligned_time
            print("[DATA-DEBUG] Normal collection - time aligned to minute: {}".format(collection_time))
        else:
            # 紧急采集使用实际时间
            print("[DATA-DEBUG] Emergency collection - using actual time: {}".format(collection_time))
        
        # 获取电池电压(使用ADC电源电压)
        battery_voltage = round(float(adc_data.get("power_voltage", 0.0)), 2)
        
        # 获取市电状态(DI1状态: 1表示有市电，0表示断电)
        # DI1通过上拉电阻连接，正常情况下为高电平(1)，断电时为低电平(0)
        di1_value = adc_data.get("di1", -999)
        print("[DATA-DEBUG] DI1 raw value: {}, adc_data: {}".format(di1_value, adc_data))
        
        if di1_value == -999:
            # 无数据时默认为有电
            power_status = 1
        else:
            # DI1=1表示有电，DI1=0表示断电
            power_status = 1 if di1_value == 1 else 0
        
        print("[DATA-DEBUG] Power status (OO): {} (di1={})".format(power_status, di1_value))
        
        # 获取异常用电状态
        bks_status = 0  # 默认正常
        # 检查电流是否异常
        current_value = float(modbus_data.get("current", 0.0))
        current_warning_value = rtu_config.get_config("warning.current_warning_value", 80)
        if current_value > current_warning_value:
            bks_status = 1  # 异常
        
        # 格式化时间字符串
        tm = utime.localtime(collection_time)
        datetime_str = "{:04d}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}".format(
            tm[0], tm[1], tm[2], tm[3], tm[4], tm[5])
        
        # 构建新格式的数据
        data = {
            "TT": collection_time,  # 时间戳
            "PHO": str(device_sn),  # 主机编号
            "HDV": hardware_version,  # 硬件版本编号
            "SV": software_version,  # ROM版本
            "NO": _packet_sequence,  # 包序列号
            "RS": system_data.get("signal_strength", 0),  # GPRS信号值
            "IMEI": imei,  # IMEI号
            "CNUM": cnum,  # 电话号码
            "CCID": ccid,  # CCID号
            "BAT": battery_voltage,  # 电池电压
            "ROM": 0,  # ROM参考值
            "RAM": 0,  # RAM参考值
            "OO": power_status,  # 市电标识
            "LONG": -999,  # 经度(设备无此功能)
            "LAT": -999,  # 纬度(设备无此功能)
            "DIR": -999,  # 方向(设备无此功能)
            "SP": -999,  # 速度(设备无此功能)
            "TEMP": round(float(modbus_data.get("temperature", -999.0)), 1),  # 温度
            "HUMI": round(float(modbus_data.get("humidity", -999.0)), 1),  # 湿度
            "VLT": round(float(modbus_data.get("voltage", -999.0)), 1),  # 电表电压
            "ENGY": round(float(modbus_data.get("energy", -999.0)), 1),  # 累计能耗
            "CURR": round(float(modbus_data.get("current", -999.0)), 1),  # 当前电流
            "BKS": bks_status,  # 异常用电预警状态
            "datetime": datetime_str,  # 可读时间格式(方便调试)
            # 三相电压数据
            "AVLT": round(float(modbus_data.get("voltage_a", -999.0)), 1),  # A相电压
            "BVLT": round(float(modbus_data.get("voltage_b", -999.0)), 1),  # B相电压
            "CVLT": round(float(modbus_data.get("voltage_c", -999.0)), 1),  # C相电压
            # 三相电流数据
            "ACURR": round(float(modbus_data.get("current_a", -999.0)), 3),  # A相电流
            "BCURR": round(float(modbus_data.get("current_b", -999.0)), 3),  # B相电流
            "CCURR": round(float(modbus_data.get("current_c", -999.0)), 3),  # C相电流
            # 保留原有字段供调试
            "signal_strength": system_data.get("signal_strength", 0),
            "adc_power": adc_data.get("di1", -999),
            "adc_volt": battery_voltage,
            "debug": modbus_data.get("debug", "--"),
        }
        
        return data
        
    except Exception as e:
        print("[DATA] Format server data error: {}".format(e))
        # 递增包序列号(即使出错也要递增)
        _packet_sequence = (_packet_sequence % 65535) + 1
        
        # 获取当前时间
        current_time = utime.time()
        tm = utime.localtime(current_time)
        datetime_str = "{:04d}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}".format(
            tm[0], tm[1], tm[2], tm[3], tm[4], tm[5])
        
        # 返回新格式的默认数据
        return {
            "TT": current_time,  # 时间戳
            "PHO": str(rtu_config.get_device_sn()),  # 主机编号
            "HDV": "1",  # 硬件版本编号
            "SV": rtu_config.get_config("system.version", "1.0.0"),  # ROM版本
            "NO": _packet_sequence,  # 包序列号
            "RS": 0,  # GPRS信号值
            "IMEI": "",  # IMEI号
            "CNUM": "",  # 电话号码
            "CCID": "",  # CCID号
            "BAT": 0.0,  # 电池电压
            "ROM": 0,  # ROM参考值
            "RAM": 0,  # RAM参考值
            "OO": 0,  # 市电标识(默认断电)
            "LONG": -999,  # 经度
            "LAT": -999,  # 纬度
            "DIR": -999,  # 方向
            "SP": -999,  # 速度
            "TEMP": -999.0,  # 温度
            "HUMI": -999.0,  # 湿度
            "VLT": -999.0,  # 电表电压
            "ENGY": -999.0,  # 累计能耗
            "CURR": -999.0,  # 当前电流
            "BKS": 0,  # 异常用电预警状态(默认正常)
            "datetime": datetime_str,  # 可读时间格式(方便调试)
            # 三相电压数据
            "AVLT": -999.0,  # A相电压
            "BVLT": -999.0,  # B相电压
            "CVLT": -999.0,  # C相电压
            # 三相电流数据
            "ACURR": -999.0,  # A相电流
            "BCURR": -999.0,  # B相电流
            "CCURR": -999.0,  # C相电流
            # 保留原有字段供调试
            "signal_strength": 0,
            "adc_power": -999,
            "adc_volt": 0.0,
            "debug": "--",
        }

def _collect_system_data():
    """采集系统数据"""
    try:
        import gc
        
        return {
            "network_connected": rtu_config.g_network_ready,
            "mqtt_connected": rtu_config.g_mqtt_connected,
            "memory_free": gc.mem_free(),
            "system_status": rtu_config.g_system_status,
            "signal_strength": rtu_network.get_signal_strength() if rtu_network.is_connected() else 0
        }
    except Exception as e:
        print("[DATA] System data collection error: {}".format(e))
        return {}

def upload_data():
    """上传数据（主要用于上传缓存的离线数据）"""
    if not rtu_config.g_mqtt_connected:
        print("[DATA] MQTT not connected, skipping upload")
        return False
    
    try:
        uploaded_count = 0
        
        # 只上传缓存的离线数据
        print("[DATA-DEBUG] Checking cached data...")
        cached_data = rtu_storage.get_cached_data()
        
        if cached_data:
            print("[DATA-DEBUG] Found {} cached items".format(len(cached_data)))
            
            cache_uploaded = 0
            # 使用索引方式遍历缓存数据
            cache_to_upload = cached_data[:5]  # 每次最多上传5条
            for i in range(len(cache_to_upload)):
                cached_item = cache_to_upload[i]
                print("[DATA-DEBUG] Uploading cached item {}".format(i))
                
                # 处理缓存数据格式
                if isinstance(cached_item, dict) and "data" in cached_item:
                    upload_data_item = cached_item["data"]
                else:
                    upload_data_item = cached_item
                
                if rtu_mqtt.publish_data(upload_data_item):
                    cache_uploaded += 1
                    uploaded_count += 1
                else:
                    print("[DATA-DEBUG] Failed to upload cached item {}".format(i))
                    break
            
            # 清空已上传的缓存
            if cache_uploaded > 0:
                print("[DATA-DEBUG] Clearing {} uploaded items from cache".format(cache_uploaded))
                remaining_cache = cached_data[cache_uploaded:]
                rtu_storage.clear_cache()
                for item in remaining_cache:
                    # 处理缓存数据格式
                    if isinstance(item, dict) and "data" in item:
                        rtu_storage.cache_data(item["data"])
                    else:
                        rtu_storage.cache_data(item)
        
        if uploaded_count > 0:
            print("[DATA] Uploaded {} cached data items".format(uploaded_count))
        
        return uploaded_count > 0
        
    except Exception as e:
        print("[DATA] Data upload error: {}".format(e))
        print("[DATA] Error type: {}".format(type(e)))
        return False


def get_latest_data():
    """获取最新数据"""
    # 由于不再使用缓冲区，返回None
    return None

def get_data_statistics():
    """获取数据统计"""
    try:
        storage_stats = rtu_storage.get_storage_stats()
        cache_count = storage_stats.get("cache_count", 0) if storage_stats else 0
        
        return {
            "buffer_count": 0,  # 不再使用缓冲区
            "cache_count": cache_count,
            "last_collection_time": _last_collection_time,
            "total_pending": cache_count
        }
    except Exception as e:
        print("[DATA] Get data statistics error: {}".format(e))
        return None

def clear_all_data():
    """清空所有数据"""
    try:
        rtu_storage.clear_cache()
        print("[DATA] All data cleared")
        return True
    except Exception as e:
        print("[DATA] Clear data error: {}".format(e))
        return False

def force_upload():
    """强制上传数据"""
    if not rtu_config.g_mqtt_connected:
        print("[DATA] MQTT not connected, cannot force upload")
        return False
    
    # 尝试上传缓存数据
    return upload_data()

def test_data_service():
    """测试数据服务"""
    print("[DATA] Testing data service...")
    
    # 测试数据采集
    data = collect_data()
    if data:
        print("[DATA] Data collection test passed: {} fields".format(len(data)))
        print("[DATA] Sample data: {}".format(data))
    else:
        print("[DATA] Data collection test failed")
    
    # 测试数据统计
    stats = get_data_statistics()
    if stats:
        print("[DATA] Data statistics: {}".format(stats))
    
    # 测试数据缓存
    if rtu_storage.cache_data({"test": "data"}):
        print("[DATA] Data caching test passed")
    
    print("[DATA] Data service test completed")